package com.linkit.main.article;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import android.os.AsyncTask;
import android.util.Log;

import com.linkit.model.Article;
import com.linkit.utils.Constants;

public class FacebookLinkLoader extends AsyncTask<Void, Void, String> {

	private ArticleViewHolder articleViewHolder;
	private Article article;

	public FacebookLinkLoader(Article article,
			ArticleViewHolder articleViewHolder) {
		this.article = article;
		this.articleViewHolder = articleViewHolder;
	}

	@Override
	protected String doInBackground(Void... params) {
		InputStream inputStream = null;
		HttpsURLConnection connection = null;
		String urlStr = "https://graph.facebook.com/fql?q=SELECT url, normalized_url, share_count, like_count, comment_count, total_count, commentsbox_count, comments_fbid, click_count FROM link_stat WHERE url='"
				+ article.linkComments + "'";
		Log.e("", "URL 1 = " + urlStr);
		String data = "";

		try {
			

			final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

				@Override
				public X509Certificate[] getAcceptedIssuers() {
					// TODO Auto-generated method stub
					return null;
				}

				@Override
				public void checkServerTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
					// TODO Auto-generated method stub

				}

				@Override
				public void checkClientTrusted(X509Certificate[] chain,
						String authType) throws CertificateException {
					// TODO Auto-generated method stub

				}
			} };

			// Install the all-trusting trust manager
			final SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
			// Create an ssl socket factory with our all-trusting manager
			final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

			if (urlStr.startsWith("https://")) {
				HttpsURLConnection
						.setDefaultHostnameVerifier(new HostnameVerifier() {
							
							@Override
							public boolean verify(String hostname, SSLSession session) {
								// TODO Auto-generated method stub
								return true;
							}
						});
			}

			URL url = new URL(urlStr);
			System.setProperty("http.keepAlive", "false");
			connection = (HttpsURLConnection)url.openConnection();
			connection.setSSLSocketFactory(sslSocketFactory);
			connection.setDoOutput(true);
			connection.setConnectTimeout(15000 /* milliseconds */);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Charset", Constants.CHARSET);
			connection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded;charset=" + Constants.CHARSET);
			

			// Kết nối đến tài nguyên
			connection.connect();

			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				// Reading data from url
				inputStream = connection.getInputStream();

				BufferedReader br = new BufferedReader(new InputStreamReader(
						inputStream));

				StringBuffer sb = new StringBuffer();

				String line = "";
				while ((line = br.readLine()) != null) {
					sb.append(line);
				}

				data = sb.toString().trim();

				br.close();

			} else {
				Log.e(Constants.TAG,
						"Response Code:" + connection.getResponseCode());
			}

		} catch (Exception e) {
			Log.e("", "URL = " + urlStr, e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
				}
			}

			if (connection != null) {
				connection.disconnect();
			}

		}
		return data;
	}

	@Override
	protected void onPostExecute(String data) {
		if (data != null) {
			Log.e("", "data ==" + data);
		}
	}

	
}
